package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.Comments;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.CommentsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 评论接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/comments")
@Slf4j
public class CommentsController {

    @Resource
    private CommentsService commentsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建评论
     *
     * @param comments
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addComment(@RequestBody Comments comments, HttpServletRequest request) {
        if (comments == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        comments.setUser_id(loginUser.getId());
        comments.setLike_count(0);
        comments.setReply_count(0);
        comments.setStatus(1); // 1正常
        boolean result = commentsService.save(comments);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCommentId = comments.getId();
        return ResultUtils.success(newCommentId);
    }

    /**
     * 删除评论
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Comments oldComment = commentsService.getById(id);
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldComment.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = commentsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新评论（仅管理员）
     *
     * @param comments
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateComment(@RequestBody Comments comments) {
        if (comments == null || comments.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comments oldComment = commentsService.getById(comments.getId());
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = commentsService.updateById(comments);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取评论
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Comments> getCommentById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comments comment = commentsService.getById(id);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(comment);
    }

    /**
     * 根据目标获取评论列表
     *
     * @param targetType 目标类型: 1文章 2沸点
     * @param targetId 目标ID
     * @param current 当前页
     * @param size 页大小
     * @return
     */
    @GetMapping("/list/target")
    public BaseResponse<Page<Comments>> getCommentsByTarget(
            @RequestParam Integer targetType,
            @RequestParam Long targetId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (targetType == null || targetId == null || targetId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<Comments> commentPage = commentsService.lambdaQuery()
                .eq(Comments::getTarget_type, targetType)
                .eq(Comments::getTarget_id, targetId)
                .eq(Comments::getStatus, 1) // 只显示正常状态的评论
                .orderByDesc(Comments::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(commentPage);
    }

    /**
     * 分页获取评论列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Comments>> listCommentByPage(@RequestParam long current, @RequestParam long size) {
        Page<Comments> commentPage = commentsService.page(new Page<>(current, size));
        return ResultUtils.success(commentPage);
    }

    /**
     * 分页获取当前用户创建的评论列表
     *
     * @param current
     * @param size
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Comments>> listMyCommentByPage(@RequestParam long current, @RequestParam long size,
            HttpServletRequest request) {
        if (current <= 0 || size <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Page<Comments> commentPage = commentsService.lambdaQuery()
                .eq(Comments::getUser_id, loginUser.getId())
                .orderByDesc(Comments::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(commentPage);
    }

    /**
     * 编辑评论（用户）
     *
     * @param comments
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editComment(@RequestBody Comments comments, HttpServletRequest request) {
        if (comments == null || comments.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comments oldComment = commentsService.getById(comments.getId());
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userService.getLoginUser(request);
        // 仅本人或管理员可编辑
        if (!oldComment.getUser_id().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = commentsService.updateById(comments);
        return ResultUtils.success(result);
    }

}